package com.relife.common.utils;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;

/**
 * 网易云信电信发送接口
 * 
 * @author WU
 * @date 2017年3月20日 下午3:15:09
 */
public class NeteaseSmsUtil {
	private static final Logger log = Logger.getLogger("NeteaseSmsUtil");
	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	/***/
	private static final String SEND_CODE_URL = "https://api.netease.im/sms/sendcode.action";
	/***/
	private static final String SEND_TEMPLATE_URL = "https://api.netease.im/sms/sendtemplate.action";

	/**
	 * 发送验证码
	 * 
	 * @author WU
	 * @date 2017年3月20日 下午3:11:44
	 * @param appKey
	 * @param appSecret
	 * @param mobile
	 */
	public static void sendCode(String appKey, String appSecret, String mobile) {
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(SEND_CODE_URL);

			String nonce = StringUtil.getRandom(32);
			String curTime = String.valueOf((new Date()).getTime() / 1000L);
			String checkSum = getCheckSum(appSecret, nonce, curTime);// 参考

			// 设置请求的header
			httpPost.addHeader("AppKey", appKey);
			httpPost.addHeader("Nonce", nonce);
			httpPost.addHeader("CurTime", curTime);
			httpPost.addHeader("CheckSum", checkSum);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

			// 设置请求的参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("mobile", mobile));
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			// 执行请求
			HttpResponse response = httpClient.execute(httpPost);
			log.info(EntityUtils.toString(response.getEntity(), "utf-8"));
		} catch (Exception e) {
			log.error(StringUtil.exception2String(e));
		}
	}

	/**
	 * 根据模版ID发送短信
	 * 
	 * @author WU
	 * @date 2017年3月20日 下午3:14:22
	 * @param appKey
	 * @param appSecret
	 * @param mobiles
	 * @param params
	 * @param templateid
	 */
	public static void sendTemplate(String appKey, String appSecret, JSONArray mobiles, JSONArray params, String templateid) {
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(SEND_TEMPLATE_URL);

			String nonce = StringUtil.getRandom(32);
			String curTime = String.valueOf((new Date()).getTime() / 1000L);
			String checkSum = getCheckSum(appSecret, nonce, curTime);// 参考

			// 设置请求的header
			httpPost.addHeader("AppKey", appKey);
			httpPost.addHeader("Nonce", nonce);
			httpPost.addHeader("CurTime", curTime);
			httpPost.addHeader("CheckSum", checkSum);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

			// 设置请求的参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();

			nvps.add(new BasicNameValuePair("templateid", templateid));
			nvps.add(new BasicNameValuePair("mobiles", mobiles.toString()));
			nvps.add(new BasicNameValuePair("params", params.toString()));
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			// 执行请求
			HttpResponse response = httpClient.execute(httpPost);
			log.info(EntityUtils.toString(response.getEntity(), "utf-8"));
		} catch (Exception e) {
			log.error(StringUtil.exception2String(e));
		}
	}

	/**
	 * 
	 * @author WU
	 * @date 2017年3月20日 下午3:02:34
	 * @param appSecret
	 * @param nonce
	 * @param curTime
	 * @return
	 */
	private static String getCheckSum(String appSecret, String nonce, String curTime) {
		return encode("sha1", appSecret + nonce + curTime);
	}

	private static String encode(String algorithm, String value) {
		if (value == null) {
			return null;
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
			messageDigest.update(value.getBytes());
			return getFormattedText(messageDigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static String getFormattedText(byte[] bytes) {
		int len = bytes.length;
		StringBuilder buf = new StringBuilder(len * 2);
		for (int j = 0; j < len; j++) {
			buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
			buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
		}
		return buf.toString();
	}
}
